import React, { useState, useEffect, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import { Button, Toast, Loading } from '@nutui/nutui-react';
import { User } from '@nutui/icons-react';
import { wechatLogin, checkLoginStatus } from '@/store/actions/userActions';
import { isWechat, getWechatCode, getUrlParams, clearWechatAuthParams } from '@/utils/wechatAuth';
import './index.less';
import { api } from '@/api/api';

let isProcessing = false;

const Login = () => {
    const navigate = useNavigate();
    const location = useLocation();
    const dispatch = useDispatch();
    const { loading, isLogin } = useSelector((state) => state.user);
    const [localLoading, setLocalLoading] = useState(false);
    const isProcessingRef = useRef(false);

    // 获取重定向路径
    const redirectPath = location.state?.from || '/';

    // 微信授权登录
    const handleWechatLogin = async () => {
        if (!isWechat()) {
            Toast.show('请在微信中打开');
            return;
        }

        setLocalLoading(true);

        try {
            const shopId = getUrlParams('shopId') || localStorage.getItem('shop_id');
            if (!shopId) {
                Toast.show('未配置shopId');
                return;
            }

            if (shopId) {
                // 跳转到微信授权页面
                redirectToWechatAuth(shopId);
            }
        } catch (error) {
            Toast.show('登录失败，请重试');
        } finally {
            setLocalLoading(false);
        }
    };

    // 跳转到微信授权页面
    const redirectToWechatAuth = async (shopId) => {
        const redirectUri = window.location.origin + '/shopapp/login?shopId=' + shopId;
        const res = await api.getWechatRedirectUrl({
            redirectUrl: redirectUri,
            shopId,
        });
        const authUrl = res.data;
        window.location.href = authUrl;
    };

    // 检查是否已经登录
    useEffect(() => {
        const checkLogin = async () => {
            if (isProcessingRef.current) {
                return;
            }

            const code = getWechatCode();
            const shopId = getUrlParams('shopId') || localStorage.getItem('shop_id');
            if (!shopId) {
                Toast.show('未配置shopId');
                return;
            }
            if (code) {
                isProcessingRef.current = true;
                try {
                    const result = await dispatch(wechatLogin(code, shopId));
                    if (result.success) {
                        Toast.show('登录成功');
                        clearWechatAuthParams();
                        navigate(redirectPath, { replace: true });
                    } else {
                        throw new Error(result.error || '登录失败');
                    }
                } catch (error) {
                    Toast.show('登录失败，请重试');
                } finally {
                    isProcessingRef.current = false;
                }
                return;
            }

            // 如果没有code，检查是否已经登录
            const isLoggedIn = await dispatch(checkLoginStatus());
            if (isLoggedIn) {
                navigate(redirectPath, { replace: true });
            }
        };

        checkLogin();
    }, [navigate, redirectPath, dispatch]);

    return (
        <div className="login-container">
            <div className="login-content">
                {/* Logo区域 */}
                <div className="login-logo">
                    <h1 className="logo-title">数字门店</h1>
                    <p className="logo-subtitle">欢迎使用微信登录</p>
                </div>

                {/* 登录按钮区域 */}
                <div className="login-actions">
                    <Button
                        type="primary"
                        size="large"
                        block
                        icon={<User />}
                        loading={loading || localLoading}
                        onClick={handleWechatLogin}
                        className="wechat-login-btn"
                    >
                        {loading || localLoading ? '登录中...' : '微信授权登录'}
                    </Button>

                    <div className="login-tips">
                        <p>• 请确保在微信环境中打开</p>
                        <p>• 授权后即可使用全部功能</p>
                    </div>
                </div>

                {/* 底部信息 */}
                <div className="login-footer">
                    <p>登录即表示同意《用户协议》和《隐私政策》</p>
                </div>
            </div>

            {/* 加载遮罩 */}
            {(loading || localLoading) && (
                <div className="login-loading">
                    <Loading type="spinner" />
                    <p>正在处理登录...</p>
                </div>
            )}
        </div>
    );
};

export default Login;
